<?php

namespace app\master\controller;

use think\Loader;
use think\Validate;

class Base extends PublicController
{

    public function _initialize()
    {
        //当前方法
        $sence = request()->action();
        $controller = request()->controller();
        $action = request()->module() . "/" . $controller . "/" . $sence;
        //判断登陆状态
        if (!$this->checkLogin()) {
            $url = request()->url();
            $this->error('请登录系统', url('user/login') . "?url=" . urlencode($url));
        }

//        if (!$this->checkAuth($action)) {
//            return $this->error('权限不足');
//        }

        model("system_log")->addLog();

        $exists = APP_PATH . "common/validate/" . $controller . ".php";
        if (file_exists($exists)) {
            $validate = validate($controller);
            $result = $validate->hasScene($sence);

            if ($result && request()->post()) {
                $data = input("post.");
                $msg = $validate->scene($sence)->check($data);
                if (!$msg) $this->ajaxReturn(603, $validate->getError());
            }
        }
        //向所有页面中传入当前页面的使用者和当前页面的方法
        $this->assign('username', session('admin_name'));
        $this->assign('action', $action);
        //获取顶部菜单
        $this->assign('top_menu', '');
        //获取左侧菜单
        $admin_info = db('admin_info')->where('admin_id', session('admin_id'))->find();
        $this->assign('admin_info', $admin_info);
        $left_menu = model('permission')->getLeftMenu($action);
        $this->assign('left_menu', $left_menu);
    }

    /**
     * 检测登陆状态
     * @return bool
     */
    public function checkLogin()
    {
        if (session('admin_id')) {
            return true;
        };
        return false;
    }


    public function checkAuth($action)
    {
        $id = db('permission')->where(['rule' => $action])->find();
        $arr = db('role_permission')->where(['role_id' => session('role_id')])->column('permission_id');
        if (in_array($id['permission_id'], $arr)) {
            return true;
        }
        return false;
    }
}